package pfc.view;

import java.awt.Color;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.BorderFactory;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.WindowConstants;

import org.apache.log4j.Logger;

import pfc.view.control.GeraMenuAplicacao;
import pfc.view.model.Icons;
import pfc.view.view.MyDesktopPane;

public class Main extends JFrame {

	public static String VERSION = "1.0";

	private static final String DIRECTORY_MAP_FILENAME = "directoryMap";

	private static final int MAX_WAIT_SEC = 10;

	private static final Logger logger = Logger.getLogger(Main.class); // @jve:decl-index=0:

	private static final long serialVersionUID = 1L;

	private JMenuBar jJMenuBarMenuBar = null;

	public static JDesktopPane panel;

	public static Main instance;

	public static Object canCloseMutex = new Object();

	/**
	 * ThreadGroup pra tratar erros internos nas thread de execução das
	 * tarefas.
	 */
	public static ThreadGroup tg = new ThreadGroup("Processamentos") {

		public void uncaughtException(Thread t, Throwable e) {
			logger.error("Erro na execução de uma Job, Thread: "
					+ t.getName(), e);
			JOptionPane
					.showMessageDialog(
							Main.instance,
							"Um erro interno ocorreu.\n"
									+ "Por favor contate o suporte, enviando o arquivo de log.",
							"Erro fatal", JOptionPane.ERROR_MESSAGE);
		}

	};

	/**
	 * This method initializes
	 */
	public Main() {
		super();
		initialize();
	}

	/**
	 * This method initializes this s
	 */
	private void initialize() {

		// Setando os diretórios padrão das telas...

		// Botões em português
		UIManager.put("OptionPane.yesButtonText", "Sim");
		UIManager.put("OptionPane.cancelButtonText", "Cancelar");
		UIManager.put("OptionPane.noButtonText", "Não");
		UIManager.put("OptionPane.okButtonText", "OK");

		UIManager.put("FileChooser.lookInLabelMnemonic", "E");
		UIManager.put("FileChooser.lookInLabelText", "Examinar em");

		UIManager.put("FileChooser.saveInLabelMnemonic", "L");
		UIManager.put("FileChooser.saveInLabelText", "Salvar em");

		UIManager.put("FileChooser.upFolderToolTipText", "Um nível acima");
		UIManager.put("FileChooser.upFolderAccessibleName", "Um nível acima");

		UIManager.put("FileChooser.homeFolderToolTipText", "Desktop");
		UIManager.put("FileChooser.homeFolderAccessibleName", "Desktop");

		UIManager.put("FileChooser.newFolderToolTipText", "Criar nova pasta");
		UIManager
				.put("FileChooser.newFolderAccessibleName", "Criar nova pasta");

		UIManager.put("FileChooser.listViewButtonToolTipText", "Lista");
		UIManager.put("FileChooser.listViewButtonAccessibleName", "Lista");

		UIManager.put("FileChooser.detailsViewButtonToolTipText", "Detalhes");
		UIManager
				.put("FileChooser.detailsViewButtonAccessibleName", "Detalhes");

		UIManager.put("FileChooser.fileNameLabelMnemonic", "N");
		UIManager.put("FileChooser.fileNameLabelText", "Nome do arquivo");

		UIManager.put("FileChooser.filesOfTypeLabelMnemonic", "T");
		UIManager.put("FileChooser.filesOfTypeLabelText", "Arquivos do tipo");

		UIManager.put("FileChooser.fileNameHeaderText", "Nome");
		UIManager.put("FileChooser.fileSizeHeaderText", "Tamanho");
		UIManager.put("FileChooser.fileTypeHeaderText", "Tipo");
		UIManager.put("FileChooser.fileDateHeaderText", "Data");
		UIManager.put("FileChooser.fileAttrHeaderText", "Atributos");

		UIManager.put("FileChooser.cancelButtonText", "Cancelar");
		UIManager.put("FileChooser.cancelButtonMnemonic", "C");
		UIManager.put("FileChooser.cancelButtonToolTipText", "Cancelar");

		UIManager.put("FileChooser.openButtonText", "Abrir");
		UIManager.put("FileChooser.openButtonMnemonic", "B");
		UIManager.put("FileChooser.openButtonToolTipText", "Abrir");

		UIManager.put("FileChooser.directoryOpenButtonText", "Abrir");
		UIManager.put("FileChooser.directoryOpenButtonMnemonic", "B");
		UIManager.put("FileChooser.directoryOpenButtonToolTipText", "Abrir");

		UIManager.put("FileChooser.saveButtonText", "Salvar");
		UIManager.put("FileChooser.saveButtonMnemonic", "S");
		UIManager.put("FileChooser.saveButtonToolTipText", "Salvar");

		UIManager.put("FileChooser.updateButtonText", "Alterar");
		UIManager.put("FileChooser.updateButtonMnemonic", "A");
		UIManager.put("FileChooser.updateButtonToolTipText", "Alterar");

		UIManager.put("FileChooser.helpButtonText", "Ajuda");
		UIManager.put("FileChooser.helpButtonMnemonic", "J");
		UIManager.put("FileChooser.helpButtonToolTipText", "Ajuda");

		UIManager.put("FileChooser.acceptAllFileFilterText",
				"Todos os arquivos");

		setIconImage(Icons.ICONEVALE.getImage());

		panel = new MyDesktopPane();
		panel.setBackground(Color.LIGHT_GRAY);
		panel.setBorder(BorderFactory.createEtchedBorder());

		getContentPane().add(panel, java.awt.BorderLayout.CENTER);
		setVisible(true);
		this.setJMenuBar(getJJMenuBarMenuBar());
		this.setTitle("SAFCP");
		setExtendedState(JFrame.MAXIMIZED_BOTH);
		setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
		addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				onClose(e);
			}
		});
//		ScreenManager.manage(new TelaLogin(this));

	}

	protected void onClose(WindowEvent e) {

		synchronized (Main.canCloseMutex) { // não pode fechar se alguém
											// estiver
			// locando a instancia do main

//			Runnable exit = new Runnable() {
//				public void run() {
//					// Salvando os diretórios padrão das telas...
//					Map m = JFileChooserLastDirectoryAware
//							.getLastDirectoryMap();
//					GeradorArquivoBinario.gravaArquivo(m,
//							DIRECTORY_MAP_FILENAME);
//					logger.info("Banco de dados COADF versão " + VERSION
//							+ " finalizado.");
//					System.exit(0);
//				}
//			};

//			DatabaseController.salvarDados(this, exit);
			logger.info("Aplicação QRCode versão " + VERSION + " finalizada.");
			System.exit(0);

		}
	}

	/**
	 * This method initializes jMenuMenuCadastro
	 * 
	 * @return javax.swing.JMenu
	 */
	/*
	 * public JMenu getJMenuMenuCadastro() { if (jMenuMenuCadastro == null) {
	 * jMenuMenuCadastro = new JMenu(); jMenuMenuCadastro.setText("Cadastro");
	 * item = new JMenuItemValidator(null); item.setText("Usuários");
	 * jMenuMenuCadastro.add(item); item.addActionListener(new ActionListener(){
	 * public void actionPerformed(ActionEvent e) { ScreenManager.manage(new
	 * CadastroUsuario()); } }); } return jMenuMenuCadastro; }
	 */
	/**
	 * This method initializes jJMenuBarMenuBar
	 * 
	 * @return javax.swing.JMenuBar
	 */
	public JMenuBar getJJMenuBarMenuBar() {
		if (jJMenuBarMenuBar == null) {
			GeraMenuAplicacao geraMenu = GeraMenuAplicacao.getInstance();
			jJMenuBarMenuBar = new JMenuBar();
			jJMenuBarMenuBar.add(geraMenu.geraMenuBar());
		}
		return jJMenuBarMenuBar;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		logger.info("Iniciando aplicação QRCode versão " + VERSION);

//		com.jidesoft.utils.Lm.verifyLicense("Visagio", "SPD",
//				"E1e9MAX1KpRd8Yf8hg:tNqqFmD.CPxp1");
		try {
			// Default
			// String plaf = "com.jgoodies.looks.plastic.PlasticXPLookAndFeel";
			// UIManager.setLookAndFeel(plaf);

			// JGoodies
			// UIManager.setLookAndFeel(new
			// com.jgoodies.looks.windows.WindowsLookAndFeel());

			// Look And Feel do sistema
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

			// NimROD
			// UIManager.setLookAndFeel(new NimRODLookAndFeel());

			// QuaQua - É para Mac OS X
			// UIManager.setLookAndFeel("ch.randelshofer.quaqua.QuaquaLookAndFeel");

			// Tiny - Recomendo
			// UIManager.setLookAndFeel(new TinyLookAndFeel());

			// InfoNode
			// UIManager.setLookAndFeel(new InfoNodeLookAndFeel());

			// NapkinLook
			// UIManager.setLookAndFeel(new NapkinLookAndFeel());

			// SkinLook
			/*
			 * Skin theSkinToUse =
			 * SkinLookAndFeel.loadThemePack(Resource.class.getResourceAsStream
			 * ("xplunathemepack.zip")); SkinLookAndFeel.setSkin(theSkinToUse);
			 * UIManager.setLookAndFeel(new SkinLookAndFeel());
			 */
		} catch (Exception e) {

			logger.error("Não foi possível setar o look and feel.", e);
		}

		SwingUtilities.invokeLater(new Runnable() {
			public void run() {

				Runnable runAfter = new Runnable() { // Isso inicia a tela,
					// roda depois de
					// caregar o banco
					public void run() {
						instance = new Main();
						logger.info("Tela da aplicação QRCode versão "
								+ VERSION + " instanciada!");
					}
				};
				
				runAfter.run();
			}
		});
	}
}
